package com.bee.gateway.controller.web;

import com.bee.commons.vo.Result;
import com.bee.commons.web.constrants.WebConst;
import com.bee.gateway.common.domain.RoutesDO;
import com.bee.gateway.common.dto.RoutesDTO;
import com.bee.gateway.common.vo.RouteQueryVO;
import com.bee.gateway.common.vo.RouteVO;
import com.bee.gateway.service.RoutesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Damin.yang
 * @date 2019/07/31 14:01
 */
@Slf4j
@Api(tags = "路由配置管理")
@RestController
@RequestMapping(WebConst.MANAGEMENT + "/routes")
public class RoutesController {

	@Autowired
	private RoutesService routesService;

	@ApiOperation(value = "新增网关路由", notes = "新增网关路由")
	@PostMapping("/create")
	public Result<?> createRoute(
			@ApiParam("路由对象") @Valid @RequestBody RouteVO routeVO
	) {
		RoutesDO routesDO = routeVO.toDO();
		routesService.insert(routesDO);
		return Result.success(null);
	}

	@ApiOperation(value = "删除网关路由", notes = "根据id删除网关路由")
	@DeleteMapping("/{id}")
	public Result<?> delete(
			@ApiParam("网关路由ID") @PathVariable long id
	) {
		routesService.delete(id);
		return Result.success(null);
	}

	@ApiOperation(value = "修改网关路由", notes = "修改网关路由信息")
	@PutMapping("/{id}")
	public Result<?> update(
			@ApiParam("网关路由ID") @PathVariable long id,
			@ApiParam("网关路由对象") @Valid @RequestBody RouteVO routeVO
	) {
		RoutesDO routesDO = routeVO.toDO();
		routesDO.setId(id);
		routesService.update(routesDO);
		return Result.success(null);
	}

	@ApiOperation(value = "获取网关路由", notes = "根据id获取指定网关路由信息")
	@GetMapping("/{id}")
	public Result get(
			@ApiParam("网关路由ID") @PathVariable long id
	) {
		log.info("get with id:{}", id);
		return Result.success(new RoutesDTO(routesService.get(id)));
	}

	@ApiOperation(value = "根据uri获取网关路由", notes = "根据uri获取网关路由信息，简单查询")
	@GetMapping("/query")
	public Result<RoutesDTO> get(
			@ApiParam("网关路由路径") @RequestParam String uri
	) {
		List<RoutesDTO> dtos = routesService.query(new RouteQueryVO(uri)).stream().map(RoutesDTO::new).collect(Collectors.toList());
		return Result.success(dtos.stream().findFirst().get());
	}

	@ApiOperation(value = "搜索网关路由", notes = "根据条件查询网关路由信息")
	@PostMapping(value = "/query")
	public Result<List<RoutesDTO>> search(
			@ApiParam("网关路由查询参数") @Valid RouteQueryVO queryVO
	) {
		List<RoutesDO> routes = routesService.query(queryVO);
		List<RoutesDTO> dtos = routes.stream().map(RoutesDTO::new).collect(Collectors.toList());
		return Result.success(dtos);
	}

	@ApiOperation(value = "重载网关路由", notes = "将所以网关的路由全部重载到redis中")
	@PostMapping("/overload")
	public Result<?> overload() {
		routesService.overload();
		return Result.success(null);
	}
}
